package com.scau.yangsuiyu.estore.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfoenix.controls.JFXTextField;
import com.scau.yangsuiyu.estore.controller.myComponent.IndexGoodsVBox;
import com.scau.yangsuiyu.estore.controller.myComponent.ShopGoodsHBox;
import com.scau.yangsuiyu.estore.controller.myComponent.TopSpan;
import com.scau.yangsuiyu.estore.dababases.dao.CategoryDao;
import com.scau.yangsuiyu.estore.dababases.dao.GoodsDao;
import com.scau.yangsuiyu.estore.dababases.entity.Buyer;
import com.scau.yangsuiyu.estore.dababases.entity.Category;
import com.scau.yangsuiyu.estore.dababases.entity.Goods;
import com.scau.yangsuiyu.estore.dababases.entity.User;
import com.scau.yangsuiyu.estore.service.AppService;
import de.felixroske.jfxsupport.FXMLController;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * @author suiyu_yang
 * @description Index界面的Controller
 * @date 2019-05-19 12:03
 * @email suiyu_yang@163.com
 */
@FXMLController
public class IndexViewController extends AnchorPane implements Initializable {
    private User user;
    private List<Goods> currentGoodsList;
    private int itemsPerPage = 3;

    @FXML
    private AnchorPane topSpanContainer;

    @FXML
    private HBox goodsListHBox;

    @FXML
    private Pagination pagination;

    @FXML
    private JFXTextField inputNameTF;

    @FXML
    private TreeView<String> categoryTV;

    public IndexViewController(User user) {
        this.user = user;
        loadFXML();
    }

    public IndexViewController() {
        loadFXML();
    }

    private void loadFXML() {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/IndexView.fxml"));
        fxmlLoader.setController(this);
        fxmlLoader.setRoot(this);
        try {
            fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        if (user == null) {
            topSpanContainer.getChildren().add(new TopSpan());
        } else {
            topSpanContainer.getChildren().add(new TopSpan(user));
        }
        currentGoodsList = new GoodsDao().getAllGoods();
        inputNameTF.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if (event.getCode() == KeyCode.ENTER) {
                    search();
                }
            }
        });
        updateCategoryTV();
        updatePages();
    }

    /**
     * 更新当前列表
     */
    private void updateCategoryTV() {
        List<Category> categoryList = new CategoryDao().getAllCategory();

        TreeItem<String> rootItem = new TreeItem<>();

        Map<Integer, TreeItem> parentCategoryMap = new HashMap<>();
        for (Category category : categoryList) {
            TreeItem<String> item = new TreeItem<>(category.getName());
            parentCategoryMap.put(category.getId(), item);
            if (category.getParent() == null) { //没有父类别，是根节点
                rootItem.getChildren().add(item);
                item.setExpanded(true);
            } else {
                TreeItem parentItem = parentCategoryMap.get(category.getParent().getId());
                parentItem.getChildren().add(item);
            }
        }
        categoryTV.setRoot(rootItem);

        categoryTV.setOnMouseClicked(e -> {
            String categoryName = categoryTV.getSelectionModel().getSelectedItem().getValue();
            currentGoodsList = new CategoryDao().getCategoryByName(categoryName).getGoodsList();
            updatePages();
        });
    }

    @FXML
    private void search() {
        String name = inputNameTF.getText();
        currentGoodsList = new GoodsDao().getGoodsByName(name);
        updatePages();
    }

    /**
     * 更新页面
     */
    private void updatePages() {
        goodsListHBox.getChildren().clear();

        int pageNum;
        if (currentGoodsList.size() % itemsPerPage == 0) {
            pageNum = currentGoodsList.size() / itemsPerPage;
        } else {
            pageNum = currentGoodsList.size() / itemsPerPage + 1;
        }
        pagination.setPageCount(pageNum);
        pagination.setPageFactory((Integer pageIndex) -> createPage(pageIndex));
    }

    /**
     * 创建每一页的对象
     *
     * @param pageIndex
     * @return
     */
    private HBox createPage(int pageIndex) {
        int page = pageIndex * itemsPerPage; //当前是第几个商品
        if (currentGoodsList.size() != 0) {
            goodsListHBox.getChildren().clear();
            for (int i = page; i < page + itemsPerPage; i++) {
                if (i < currentGoodsList.size() && !currentGoodsList.get(i).isDisable()) {
                    IndexGoodsVBox indexGoodsVBox = new IndexGoodsVBox(user, currentGoodsList.get(i));
                    goodsListHBox.getChildren().add(indexGoodsVBox);
                }
            }
        }
        return goodsListHBox;
    }
}